//
//  DownLoadManager.m
//  LM_DownLoadDemo
//
//  Created by lanou3g on 16/4/27.
//  Copyright © 2016年 liman. All rights reserved.
//

#import "DownLoadManager.h"

@interface DownLoadManagerTask : NSObject

@property (nonatomic, strong) LMRadioListModel *model;
@property (nonatomic, strong) MuiscDownLoadTsk *downloadTask;

@end

@implementation DownLoadManagerTask

- (NSString *)description{
    return self.model.title;
}

@end




@implementation DownLoadManager

+(instancetype)shareManager{
    static DownLoadManager *downloadManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        downloadManager = [[DownLoadManager alloc]init];
        downloadManager.array = [NSMutableArray array];
    });
    return downloadManager;
}
///添加一个下载任务
- (void)addDownloadTask:(LMRadioListModel *)model Progress:(ProgressBlock)proBlock Complete:(CompleteBlock)comBlock{
    BOOL isContain = NO;
    for (DownLoadManagerTask *task in self.array) {
        if ([task.model.title isEqualToString:model.title]) {
            isContain = YES;
        }
    }
//    包含不下载
    if (isContain) {
        return;
    }
//    下载任务
    MuiscDownLoadTsk *musicTask= [[MuiscDownLoadTsk alloc]init];
    [musicTask downloadUrl:[NSURL URLWithString:model.musicUrl ]progressBlock:proBlock complete:comBlock];
    
    DownLoadManagerTask *downLoadManagerTask = [DownLoadManagerTask new];
    downLoadManagerTask.model = model;
    downLoadManagerTask.downloadTask = musicTask;
    [self.array addObject:downLoadManagerTask];
    
}
//当前下载任务个数
- (NSInteger )count{
    return self.array.count;
}
//取标题
- (NSString *)getTitleWithIndex:(NSInteger)index{
    DownLoadManagerTask *task = self.array[index];
    return task.model.title;
}
//设置block
- (void)setProgressBlock:(ProgressBlock)proBlock CompleteBlock:(CompleteBlock)comBlock Index:(NSInteger)index{
    DownLoadManagerTask *task = self.array[index];
    [task.downloadTask setProgressBlock:proBlock];
    [task.downloadTask setCompleteBlock:^(NSString *path) {
    [self.array removeObjectAtIndex:index];
        //发通知
        [[NSNotificationCenter defaultCenter]postNotificationName:@"downloadReloadData" object:nil];
    }];

}






@end
